<template>
  <div class="profile-page">
    <div class="form-container">
      <h2 class="form-title">修改社交信息</h2>
      <form @submit.prevent="updateProfile" class="profile-form">
        <!-- 社交信息 -->
        <div class="form-section">
          <div class="form-group-row">
            <label class="input-label">GitHub</label>
            <input
                v-model="form.github"
                type="url"
                :placeholder="form.github"
                class="form-input"
            />
          </div>
           <div class="form-group-row">
            <label class="input-label">Gitee</label>
            <input
                v-model="form.gitee"
                type="url"
                :placeholder="form.gitee"
                class="form-input"
            />
          </div>
          <div class="form-group-row">
            <label class="input-label">个人网站</label>
            <input
                v-model="form.website"
                type="url"
                :placeholder="form.website"
                class="form-input"
            />
          </div>
          <div class="form-group-row">
            <label class="input-label">微博</label>
            <input v-model="form.weibo" type="text" class="form-input"/>
          </div>
          <div class="form-group-row">
            <label class="input-label">微信</label>
            <input v-model="form.wechat" type="text" class="form-input"/>
          </div>
          <div class="form-group-row">
            <label class="input-label">QQ</label>
            <input v-model="form.qq" type="text" class="form-input"/>
          </div>

          <!-- 二维码图片上传 -->
          <div class="qr-code-container">
            <div class="qrcode-container">
              <div
                  class="qrcode-item"
                  v-for="(label, key) in qrcodes"
                  :key="key"
              >
                <label class="qrcode-label">{{ label }}</label>
                <input
                    type="file"
                    :ref="el => (fileInputs[key] = el)"
                    accept="image/*"
                    class="qrcode-input"
                    @change="e => onFileChange(key, e)"
                />

                <div class="qrcode-wrapper" @click="triggerUpload(key)">
                  <img
                      :src="form[key] || defaultImage"
                      :alt="`${label}二维码`"
                      class="qrcode-img"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="countdown > 0" class="countdown-notice">
          社交信息修改成功，{{ countdown }}秒后自动返回个人中心
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="submit" :disabled="isSubmitting" class="submit-btn">
            {{ isSubmitting ? '提交中...' : '保存修改' }}
          </button>
          <button
              type="button"
              class="btn btn-go-back"
              @click="goBack"
          >返回
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import {useUserStore} from "@stores/userStore.js";

const router = useRouter();
const store = useUserStore();
const errors = ref({});
const countdown = ref(0); // 倒计时
let countdownTimer = null;
const isSubmitting = ref(false); // 提交按钮状态
const fileInputs = reactive({}); // 存储每个 input 的 refs
const form = reactive({
  github: "", // GitHub URL
  gitee: "", // Gitee URL
  website: "", // Website URL
  wechat: "", // 微信
  weibo: "", // 微博
  qq: "", // QQ
  wechat_qrcode: "", // 微信二维码
  wechat_gzh_qrcode: "", // 微信公众号二维码
  qq_qrcode: "", // QQ二维码
});

const qrcodes = reactive({
  wechat_qrcode: "微信二维码",
  wechat_gzh_qrcode: "公众号二维码",
  qq_qrcode: "QQ二维码",
});

const defaultImage =
    "https://cdn.jsdelivr.net/gh/ctripcorp/apollo@master/doc/images/qrcode.png"; // 默认图像路径

// 获取用户社交信息
const fetchProfile = async () => {
  try {
    const response = await axios.get(
        "/api/accounts/auth/user_social_update/"
    ,{ requiresAuth: true });
    Object.assign(form, {
      github: response.data.github,
      gitee: response.data.gitee,
      website: response.data.website,
      wechat: response.data.wechat,
      weibo: response.data.weibo,
      qq: response.data.qq,
      wechat_qrcode: response.data.wechat_qrcode,
      qq_qrcode: response.data.qq_qrcode,
      wechat_gzh_qrcode: response.data.wechat_gzh_qrcode,
    });
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};

// 文件选择触发后对图片进行处理
const fileObjects = reactive({}); // 新增文件对象存储

const onFileChange = (key, event) => {
  const file = event.target.files[0];
  if (file) {
    fileObjects[key] = file; // 存储原始文件对象
    const reader = new FileReader();
    reader.onload = (e) => {
      form[key] = e.target.result; // 仅用于预览
    };
    reader.readAsDataURL(file);
  }
};


// 动态触发 input 的点击事件
const triggerUpload = (key) => {
  const input = fileInputs[key];
  if (input) input.click();
};

// 提交更新
const updateProfile = async () => {
  isSubmitting.value = true;
  const formData = new FormData();
  //处理普通字段
  const { wechat_qrcode, wechat_gzh_qrcode, qq_qrcode, ...otherFields } = form;
  Object.entries(otherFields).forEach(([key, value]) => {
    formData.append(key, value);
  });

  // 处理文件字段
  Object.entries(fileObjects).forEach(([key, file]) => {
    if (file) {
      formData.append(key, file);
    }
  });
  try {
    await axios.put("/api/accounts/auth/user_social_update/", formData,{ requiresAuth: true }, {
      headers: {"Content-Type": "multipart/form-data"},
    });
    countdown.value = 3;
    countdownTimer = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
        router.go(-1);
      }
    }, 1000);
  } catch (error) {
    console.error("更新失败", error);
    if (error.response?.status === 400) {
      errors.value = error.response.data;
    }
  }
  finally {
    isSubmitting.value = false;
  }
};

const goBack = async () => {
  router.go(-1);
};

// 页面加载后获取用户信息
onMounted(() => {
  if (!store.isLoggedIn) {
    router.push("/login");
  } else {
    fetchProfile();
  }
});
onBeforeUnmount(() => {
  if (countdownTimer) clearInterval(countdownTimer);
});
</script>


<style scoped>
.profile-page {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
  margin: 40px auto;
}

.form-container {
  background: var(--profile-bg-color, #fff);
  padding: 1rem;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
}

.form-title {
  text-align: center;
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  font-weight: bold;
  color: var(--profile-title-color);
}

.form-section {
  margin: 0 0 2rem 0;
}

.form-group-row {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
  gap: 1rem;
  width: 80%;
  margin: 15px auto;
}

.input-label {
  width: 12%;
  text-align: right;
  margin-right: 1rem;
  font-weight: 500;
  color: var(--profile-label-color,#555);
}

.form-input {
  flex-grow: 1;
  padding: 0.8rem 1rem;
  font-size: 1rem;
  border: 2px solid #ddd;
  border-radius: 5px;
  background: var(--profile-input-bg-color, #fff);
}
.form-input:focus {
  outline: none;
  border-color: var(--profile-input-focus-color, #409eff);
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 1.5rem;
}

.qrcode-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 20px;
}

.qrcode-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.qrcode-label {
  font-size: 16px;
  font-weight: 500;
  color: var(--profile-label-color, #555);
}

.qrcode-wrapper {
  width: 120px;
  height: 120px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.qrcode-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: var(--profile-input-bg-color, #f5f5f5);
  border-radius: 5px;
}

.qrcode-input {
  display: none; /* 隐藏文件输入框 */
}

/* 主按钮样式 */
.submit-btn {
  background:var(--profile-btn-bg-color, linear-gradient(90deg, #409eff, #66b1ff));
  color: var(--profile-btn-text-color, #fff);
  font-size: 1rem;
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background 0.3s, transform 0.3s ease, box-shadow 0.3s;
}

.submit-btn:hover {
  background: var(--profile-btn-hover-bg-color,linear-gradient(90deg, #66b1ff, #409eff));
  color: var(--profile-btn-text-hover-color, #fff);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

.submit-btn:disabled {
  background: #d3d3d3;
  cursor: not-allowed;
  opacity: 0.7;
}

.countdown-notice {
  text-align: center;
  color: #67c23a;
  margin-top: 1rem;
  font-size: 0.9rem;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 返回按钮样式 */
.btn-go-back {
  background: var(--profile-btn-bg-color, #ffffff);
  color: var(--profile-btn-color, #409eff);
  font-size: 1rem;
  padding: 0.8rem 1.5rem;
  border: 1px solid #409eff;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s, color 0.3s, transform 0.3s ease, box-shadow 0.3s;
}

.btn-go-back:hover {
  background: var(--profile-btn-hover-bg-color,#409eff);
  color: var(--profile-btn-text-hover-color, #fff);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
